package com.cqjtu.eecs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cqjtu.eecs.entity.Academy;
import com.cqjtu.eecs.entity.Major;
import com.cqjtu.eecs.entity.Teacher;
import com.cqjtu.eecs.entity.User;
import com.cqjtu.eecs.entity.dto.TeacherDto;
import com.cqjtu.eecs.entity.params.teacher.TeacherAddParams;
import com.cqjtu.eecs.entity.params.teacher.TeacherUpdateParams;
import com.cqjtu.eecs.entity.params.user.UserParams;
import com.cqjtu.eecs.entity.vo.TeacherCodeNameVo;
import com.cqjtu.eecs.entity.vo.TeacherVo;
import com.cqjtu.eecs.exception.AcademyNotFoundException;
import com.cqjtu.eecs.exception.InsertTeacherErrorException;
import com.cqjtu.eecs.mapper.MajorMapper;
import com.cqjtu.eecs.mapper.TeacherMapper;
import com.cqjtu.eecs.service.IAcademyService;
import com.cqjtu.eecs.service.ITeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqjtu.eecs.service.IUserService;
import com.cqjtu.eecs.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 教师 服务实现类
 * </p>
 *
 * @author    
 * @since 2022-03-07
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements ITeacherService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IAcademyService academyService;

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private MajorMapper majorMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importTeacherExcelInfo(List<TeacherDto> teacherDtoList) {
        List<Teacher> teacherList = new ArrayList<>();
        // teacherDto转teacher
        teacherDtoList.forEach(item -> {
            Teacher teacher = new Teacher();
            teacher.setTeacherCode(item.getTeacherCode());
            teacher.setTeacherName(item.getTeacherName());
            // 获取教师所属学院编号
            Academy academy = academyService.getOne(new QueryWrapper<Academy>().eq("academy_name", item.getAcademyName()));
            if (academy == null)
                throw new AcademyNotFoundException("学院不存在，请核查信息后重新上传");
            teacher.setAcademyId(academy.getAcademyId());

            //为教师创建默认用户
            Integer uid = createUserForTeacher(item.getTeacherCode());
            teacher.setUid(uid);
            teacherList.add(teacher);
        });

        boolean saveBatch = this.saveBatch(teacherList);
        if (!saveBatch)
            throw new InsertTeacherErrorException("添加教师信息失败，请核查教师信息后重新上传");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addATeacherInfo(TeacherAddParams teacherAddParams) {

        // 为教师创建默认用户并返回uid
        Integer uid = createUserForTeacher(teacherAddParams.getTeacherCode());

        //新建教师对象
        Teacher teacher = new Teacher();
        teacher.setUid(uid);
        teacher.setTeacherName(teacherAddParams.getTeacherName());
        teacher.setTeacherCode(teacherAddParams.getTeacherCode());
        teacher.setAcademyId(teacherAddParams.getAcademyId());
        boolean save = this.save(teacher);
        if (!save) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error();
        }
        return Result.success();
    }

    /**
     * 分页获取全部教师信息
     * @param current 当前第几页
     * @param size 每页大小
     * @param academyName
     * @return
     */
    @Override
    public Page<TeacherVo> getAllTeacherInfo(Long current, Long size, String academyName) {
        Page<TeacherVo> teacherVoPage = null;
        try {
            teacherVoPage = teacherMapper.getAllTeacherInfo(new Page<TeacherVo>(current, size), academyName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return teacherVoPage;
    }

    /**
     * 修改教师信息
     * @param teacherUpdateParams
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateTeacherInfo(TeacherUpdateParams teacherUpdateParams) {
        //查询修改前的教师信息
        Teacher old = this.getOne(new QueryWrapper<Teacher>().eq("teacher_code", teacherUpdateParams.getOldTeacherCode()));
        if (old == null)
            return Result.error(-1, "该教师信息不存在");

        // 修改了教师工号
        if (teacherUpdateParams.getTeacherCode() != null && !teacherUpdateParams.getTeacherCode().equals("") && !old.getTeacherCode().equals(teacherUpdateParams.getTeacherCode())) {
            // 修改教师对应的默认用户的username
            boolean update = userService.update(new UpdateWrapper<User>().eq("username", old.getTeacherCode()).set("username", teacherUpdateParams.getTeacherCode()));
            if (!update)
                return Result.error();
        }

        //修改教师信息
        int update = teacherMapper.updateTeacherInfo(teacherUpdateParams);
        if (update >= 1)
            return Result.success();
        return Result.error();
    }

    @Override
    public Teacher selectTeacherByTeacherCode(String teacherCode) {
        return teacherMapper.selectTeacherByTeacherCode(teacherCode);
    }

    /**
     * 根据专业代码查询该学院所有教师工号姓名
     * @param majorCode
     * @return
     */
    @Override
    public List<TeacherCodeNameVo> getTeacherCodeNameVoByMajorCode(String majorCode) {
        try {
            Major major = majorMapper.selectOne(new QueryWrapper<Major>().eq("major_code", majorCode));
            if (major == null)
                return null;

            List<TeacherCodeNameVo> teacherCodeNameVoList = teacherMapper.getTeacherCodeNameVoByMajorCode(major.getAcademyId());
            return teacherCodeNameVoList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 为教师创建默认用户并返回uid
     * @param teacherCode
     * @return
     */
    private Integer createUserForTeacher(String teacherCode) {
        //角色列表
        List<String> role = new ArrayList<>();
        role.add("teacher");

        //为教师创建默认用户
        UserParams userParams = new UserParams(teacherCode, "123456", role);
        boolean insertUserInfo = userService.saveUser(userParams);
        if(!insertUserInfo)
            throw new InsertTeacherErrorException("为教师创建用户失败，请核查教师信息后重新添加上传");

        //获取为教师创建的用户的编号
        User user = userService.getOne(new QueryWrapper<User>().eq("username", teacherCode));
        if (user == null)
            throw new InsertTeacherErrorException("为教师创建用户失败，请核查教师信息后重新添加上传");

        return user.getUid();
    }
}
